package top.llove.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.captcha.generator.MathGenerator;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.setting.Setting;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import top.llove.utils.ApiDocs;
import top.llove.utils.res.ApiResult;
import top.llove.utils.res.Result;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 公共接口
 *
 * @author: 幸会
 * @date: 2021/6/8 20:05
 * @email: 1846724873@qq.com
 * @description: 图床Controller
 * version: 1.0
 */
@Slf4j
@RestController
@RequestMapping("/public")
public class PublicController {

    @Autowired
    private RedisTemplate redisTemplate; // Redis

    /**
     * 生成API文档
     * @return
     */
    @GetMapping("/api")
    public ApiResult getApi() {
        String url = ApiDocs.generate("幸会博客", "1.0.0", "D:/dev/java/tomcat9/webapps/xh/docs/");
        return ApiResult.success(200, "生成API文档成功", url);
    }

    /**
     * 获取验证码图片
     * @param req 请求
     * @param resp 响应
     */
    @GetMapping("/verify")
    public void verify(HttpServletRequest req, HttpServletResponse resp) {
        // 获取验证码
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(250, 100, 4, 4);
        try {
            String ip = ServletUtil.getClientIP(req); // 获取访问客户端ip
            String ipMd5 = DigestUtils.md5Hex(ip); // 将获取的ipMD5加密
            log.debug("成功获取到验证码, 为: " + captcha.getCode());
            // 将获取的验证码写入redis，键为客户端ipMD5加密，值为验证码，存在时间为300秒
            redisTemplate.opsForValue().set(ipMd5, captcha.getCode(), 300, TimeUnit.SECONDS);
            // 将图片输出到浏览器
            captcha.write(resp.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
